const COS = require('cos-nodejs-sdk-v5');
const tencentcloud = require("tencentcloud-sdk-nodejs-lke");
const LkeClient = tencentcloud.lke.v20231130.Client;
const logger = require('../utils/logger');
const secretId = process.env.TCADP_SECRETID; 
const secretKey = process.env.TCADP_SECRETKEY; 
const clientConfig = {
  credential: {
    secretId: secretId,
    secretKey: secretKey
  },
  region: "ap-guangzhou",
  profile: {
    httpProfile: {
      endpoint: "lke.tencentcloudapi.com",
    },
  },
};
const client = new LkeClient(clientConfig);
const uploadToCOS = (file, appId) => {

  // 1. 将乱码字符串转换为 Buffer（假设它是 UTF-8 编码）
  const buffer = Buffer.from(file.originalname, 'binary'); // 或 'latin1'
  // 2. 用 UTF-8 解码 Buffer
  const correctName = buffer.toString('utf8');
  const ext = correctName.split('.').pop();

  return new Promise(async (resolve, reject) => {
    // console.log(data,'datadatadata');
    const params2 = {
      BotBizId: appId,
      FileType: ext,
      TypeKey: "offline",
      IsPublic: false
    };
    try {
      const data2 = await client.DescribeStorageCredential(params2);
      const cos = new COS({
        getAuthorization: (options, callback) => {
          callback({
            TmpSecretId: data2.Credentials.TmpSecretId,        // 临时密钥的 tmpSecretId
            TmpSecretKey: data2.Credentials.TmpSecretKey,      // 临时密钥的 tmpSecretKey
            SecurityToken: data2.Credentials.Token,  // 临时密钥的 sessionToken
            ExpiredTime: data2.ExpiredTime,  // 临时密钥的 sessionToken
          });
        }
      });
      cos.putObject({
        Bucket: data2.Bucket,
        Region: data2.Region,
        Key: data2.UploadPath,
        Body: file.buffer,
        ContentLength: file.size
      }, async (err, data) => {
        if (err) {
          reject(err);
        } else {
          const params = {
            BotBizId: appId,
            FileName: correctName,
            FileType: ext,
            CosUrl: data2.UploadPath,
            ETag: data.ETag,
            CosHash: data.headers['x-cos-hash-crc64ecma'],
            Size: file.size + ''
          };
          try {
            const data3 = await client.SaveDoc(params);
            resolve({
              cosData: data3
            });
          } catch (error) {
            reject(error);
          }
        }
      });
    } catch (error) {
      reject(error);
    }
  });
};

const batchUploadToCOS = async (files, appIds) => {
  const results = [];
  const appId = typeof appIds === 'string'?appIds:appIds[0];
  for (const file of files) {
    // 1. 将乱码字符串转换为 Buffer（假设它是 UTF-8 编码）
    const buffer = Buffer.from(file.originalname, 'binary'); // 或 'latin1'
    // 2. 用 UTF-8 解码 Buffer
    const correctName = buffer.toString('utf8');
    // console.log(file, correctName, 'filefilefilefilefilefile')
    try {
      const cosResult = await uploadToCOS(file, appId);
      results.push({
        originalname: correctName,
        success: true,
        message: cosResult.cosData,
      });
    } catch (error) {
      logger.error(error);
      results.push({
        originalname: correctName,
        success: false,
        message: '文件上传失败',
      });
    }
  }
  return results;
};

module.exports = {
  uploadToCOS,
  batchUploadToCOS
};
